<?php
/**
 * Created by PhpStorm.
 * User: lyq
 * Date: 2018/12/19
 * Time: 19:03
 */

namespace app\common\model;

use think\Cache;
use \think\Model;
use think\Db;

class Region extends Common
{

    /**
     *获取城市id
     * @param $city
     *
     * @return mixed
     */
    static public function getCityid($city){
        $id = Db::name('region')
            ->where('level',2)
            ->where('title','like',$city.'%')
            ->where('is_visible',1)
            ->value('id');
        if(empty($id)){
            $arr = Settings::getSettings(H_SETTINGS_GLOBAL,2);
            $id = $arr['def_city']['_id'];
        }
        return $id;
    }

    /**
     * 获取城市json
     */
    public static function getCityJson()
    {

        //判断是否存在缓存
        if (Cache::store("file")->has("city_json"))
        {
            //城市json文件
            $cityJson = Cache::store("file")->get("city_json");

        }else{
            $where = [
                'is_visible'=>1,//显示
                'parent_id'=>1,//
            ];
            $cityJson = Db::name('region')
                ->where($where)
                ->field('id as _id,title as name')
                ->order('order_num DESC,id ASC')
                ->select();
            foreach ($cityJson as &$category1)
            {
                $categoryList2 = Db::name("region")
                    ->where('is_visible',1)
                    ->where("parent_id", $category1["_id"])
                    ->order('order_num DESC,id ASC')
                    ->field('id as _id,title as name')
                    ->select();

                //获取三级分类
                foreach ($categoryList2 as &$category2)
                {
                    $categoryList3 = Db::name("region")
                        ->where('is_visible',1)
                        ->where("parent_id", $category2["_id"])
                        ->order('order_num DESC,id ASC')
                        ->field('id as _id,title as name')
                        ->select();

                    $category2["area"] = $categoryList3;
                }

                $category1["city"] = $categoryList2;
            }
            Cache::store("file")->set("city_json", $cityJson);
        }

        return $cityJson;

    }

    /**
     * 获取默认收货地址
     * @param $user_id
     * @return array|false|\PDOStatement|string|Model
     */
    static public function userAddress($user_id){
        //地址
        $address = Db::name('user_address')
            ->alias('ua')
            ->join('__REGION__ rone','rone.id=ua.pro_id')
            ->join('__REGION__ rtwo','rtwo.id=ua.city_id')
            ->join('__REGION__ rthree','rthree.id=ua.area_id')
            ->where('ua.uid',$user_id)
            ->order('ua.is_def DESC,ua.id DESC')
            ->field('ua.name,ua.mobile,ua.address,rone.title as pro,rtwo.title as city,rthree.title as area')
            ->find();
        return $address;
    }

    /**
     * 获取用户收货列表
     * @param $user_id
     * @return false|\PDOStatement|string|\think\Collection
     */
    static public function userAddressList($user_id){
        $address = Db::name('user_address')
            ->alias('ua')
            ->join('__REGION__ rone','rone.id=ua.pro_id')
            ->join('__REGION__ rtwo','rtwo.id=ua.city_id')
            ->join('__REGION__ rthree','rthree.id=ua.area_id')
            ->where('ua.uid',$user_id)
            ->order('ua.is_def DESC,ua.id DESC')
            ->field('ua.id as _id,ua.name,ua.mobile,ua.pro_id,rone.title as pro_name,ua.city_id,rtwo.title as city_name,ua.area_id,rthree.title as area_name,ua.address,ua.is_def')
            ->select();

        return $address;
    }

    /**
     * 新增收货地址
     * @param $user_id
     * @param $name
     * @param $mobile
     * @param $pro_id
     * @param $city_id
     * @param $area_id
     * @param $address
     * @param $is_def
     * @return string
     * @throws UserException
     */
    static public function userAddAddress($user_id,$name,$mobile,$pro_id,$city_id,$area_id,$address,$is_def){
        $name = remove_all_tags($name);
        if(empty($name)){
            throw new UserException('请输入联系人，避免空格等特殊字符');
        }
        if(!verify_mobile($mobile)){
            throw new UserException('请正确输入手机号码！');
        }

        if(empty($pro_id)||empty($city_id)||empty($area_id)){
            throw new UserException('地区选择有误！');
        }

        $address = remove_all_tags($address);
        if(empty($address)){
            throw new UserException('请输入详细地址，避免空格等特殊字符');
        }

        $count = Db::name('user_address')->where('uid',$user_id)->count();
        if($count>=15){
            throw new UserException('目前仅可以添加15个收货地址！');
        }

        if($is_def==1){
            //新增为默认地址将其他改为非默认
            Db::name('user_address')
                ->where('uid',$user_id)
                ->update(['is_def'=>0,'update_time'=>now_datetime()]);
        }

        $data = [
            'uid'=>$user_id,
            'name'=>$name,
            'mobile'=>$mobile,
            'pro_id'=>$pro_id,
            'city_id'=>$city_id,
            'area_id'=>$area_id,
            'address'=>$address,
            'is_def'=>$is_def,
            'update_time'=>now_datetime()
        ];
        Db::name('user_address')->insert($data);

        return '新增收货地址成功！';
    }

    /**
     * 删除收货地址
     * @param $user_id
     * @param $address_id
     * @return string
     */
    static public function userRemoveAddress($user_id,$address_id){
        if(empty($address_id)){
            throw new DeveloperException('收货地址 _id 不能为空或0！');
        }
        Db::name('user_address')
            ->where('id',$address_id)
            ->where('uid',$user_id)
            ->delete();
        return '收货地址删除成功！';
    }

    /**
     * 编辑收货地址
     * @param $user_id
     * @param $address_id
     * @param $name
     * @param $mobile
     * @param $pro_id
     * @param $city_id
     * @param $area_id
     * @param $address
     * @param $is_def
     * @return string
     * @throws DeveloperException
     * @throws UserException
     */
    static public function userEditAddress($user_id,$address_id,$name,$mobile,$pro_id,$city_id,$area_id,$address,$is_def){
        if(empty($address_id)){
            throw new DeveloperException('收货地址 _id 不能为空或0！');
        }
        $name = remove_all_tags($name);
        if(empty($name)){
            throw new UserException('请输入联系人，避免空格等特殊字符');
        }
        if(!verify_mobile($mobile)){
            throw new UserException('请正确输入手机号码！');
        }

        if(empty($pro_id)||empty($city_id)||empty($area_id)){
            throw new UserException('地区选择有误！');
        }

        $address = remove_all_tags($address);
        if(empty($address)){
            throw new UserException('请输入详细地址，避免空格等特殊字符');
        }

        if($is_def==1){
            //新增为默认地址将其他改为非默认
            Db::name('user_address')
                ->where('uid',$user_id)
                ->update(['is_def'=>0,'update_time'=>now_datetime()]);
        }

        $data = [
            'name'=>$name,
            'mobile'=>$mobile,
            'pro_id'=>$pro_id,
            'city_id'=>$city_id,
            'area_id'=>$area_id,
            'address'=>$address,
            'is_def'=>$is_def,
            'update_time'=>now_datetime()
        ];
        Db::name('user_address')->where('id',$address_id)->update($data);

        return '收货地址编辑成功！';
    }
}
